import os
import subprocess

from docx import Document
from Data import search_file


# 目录编号
def module_level_number(flag, is_only_dir):
    sysop_flag = False
    root_path = None
    if is_only_dir is None:
        filepaths = search_file.select_folder()
        return filepaths
    filepaths = search_file.select_folder()
    if filepaths == "-1":
        return "-1"
    updated_paths = filepaths
    count = 0
    for path in filepaths:
        if "维护" in path and "诊断" in path:
            return filepaths
        if "01-配置指南" in path.split('\\')[-3]:
            if count == 0:
                root_path = path.rsplit("01-配置指南", 1)[0]
            count = count + 1
            # else:
            #     print("请检查配置指南与命令参考编号")
            #     print("程序执行完成!!!")
            #     return "-1"
    scg_path = f'{root_path}01-配置指南'
    cref_path = f'{root_path}02-命令参考'
    flyleaf_path = f'{root_path}\\封面和扉页'
    # print(flyleaf_path)

    # 检查封面和扉页文件夹是否存在
    if not os.path.exists(flyleaf_path):
        print(f"\033[91m错误：找不到封面和扉页文件夹:\033[0m {flyleaf_path}")
        print("请检查配置指南与命令参考编号")
        print("程序执行完成!!!")
        sysop_flag = True
        return "-1"

    # 遍历封面和扉页文件夹
    try:
        for file in os.listdir(flyleaf_path):
            # print(file)
            if file.endswith('.docx'):
                if "配置指南" in file and "扉页" in file:
                    flyleaf = f'{flyleaf_path}\\{file}'

                    # 读取文档内容
                    doc = Document(flyleaf)
                    manual_found = False
                    content = []

                    # 遍历段落查找"手册"之后的内容
                    for para in doc.paragraphs:
                        if "以下手册" in para.text:
                            manual_found = True
                            continue
                        if manual_found and para.text.strip():
                            # 添加序号，从01开始
                            index = len(content) + 1
                            formatted_text = f"{index:02d}-{para.text.strip()}"
                            content.append(formatted_text)
                    break

        # 遍历配置指南目录
        scg_folders = []
        if os.path.exists(scg_path):
            for folder in os.listdir(scg_path):
                # if "PDF" not in folder:
                #     print(f'folder:{folder}')
                    folder_path = os.path.join(scg_path, folder)
                    if os.path.isdir(folder_path) and folder != "00-pdf":
                        scg_folders.append(folder)

            # need_rename = False
            # # 检查是否需要重命名
            # for folder in scg_folders:
            #     for name in content:
            #         if folder.split('-')[1] in name and folder.split('-')[0] != name.split('-')[0]:
            #             need_rename = True
            #             break
            #     if need_rename:
            #         break
            #
            # if need_rename:
            #     print(f"配置指南目录下的文件夹：")

            # 后续的检查和重命名逻辑保持不变
            for name in content:
                match_found = False
                for folder in scg_folders:
                    if name.split('-')[1] in folder:
                        match_found = True
                if not match_found:
                    print(f"\033[93m警告：配置指南分册 {name} 缺失\033[0m")
                    sysop_flag = True
            for folder in scg_folders:
                found_match = False
                for name in content:
                    if "-" in folder:
                        if folder.split('-')[1] in name:
                            found_match = True
                            if folder.split('-')[0] == name.split('-')[0]:
                                continue
                            else:
                                try:
                                    old_path = os.path.join(scg_path, folder)
                                    new_path = os.path.join(scg_path, name)
                                    if flag:
                                        # 使用 SVN 命令重命名
                                        subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                    else:
                                        os.rename(old_path, new_path)
                                    print(f"重命名配置指南分册: {folder} -> {name}")
                                    for i, updated_path in enumerate(updated_paths):
                                        if old_path in updated_path:
                                            updated_paths[i] = updated_path.replace(old_path, new_path)
                                except Exception as e:
                                    print(f"\033[91m重命名配置指南分册失败:\033[0m {str(e)}")
                                    sysop_flag = True
                    else:
                        if folder in name:
                            found_match = True
                            try:
                                old_path = os.path.join(scg_path, folder)
                                new_path = os.path.join(scg_path, name)
                                if flag:
                                    # 使用 SVN 命令重命名
                                    subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                else:
                                    os.rename(old_path, new_path)
                                print(f"重命名配置指南分册: {folder} -> {name}")
                                for i, updated_path in enumerate(updated_paths):
                                    if old_path in updated_path:
                                        updated_paths[i] = updated_path.replace(old_path, new_path)
                            except Exception as e:
                                print(f"\033[91m重命名配置指南分册失败:\033[0m {str(e)}")
                                sysop_flag = True
                if not found_match:
                    print(f"\033[93m警告：扉页中未找到配置指南分册 {folder}\033[0m ")
                    sysop_flag = True
        else:
            print(f"\033[91m错误：找不到配置指南目录:\033[0m {scg_path}")
            sysop_flag = True

        for file in os.listdir(flyleaf_path):
            if file.endswith('.docx'):
                if "命令参考" in file and "扉页" in file:
                    flyleaf = f'{flyleaf_path}\\{file}'

                    # 读取文档内容
                    doc = Document(flyleaf)
                    manual_found = False
                    content = []

                    # 遍历段落查找"手册"之后的内容
                    for para in doc.paragraphs:
                        if "以下手册" in para.text:
                            manual_found = True
                            continue
                        if manual_found and para.text.strip():
                            # 添加序号，从01开始
                            index = len(content) + 1
                            formatted_text = f"{index:02d}-{para.text.strip()}"
                            content.append(formatted_text)
                    break

        # 遍历命令参考目录
        scg_folders = []
        if os.path.exists(cref_path):
            for folder in os.listdir(cref_path):
                folder_path = os.path.join(cref_path, folder)
                if os.path.isdir(folder_path) and folder != "00-pdf":
                    scg_folders.append(folder)

            # need_rename = False
            # # 检查是否需要重命名
            # for folder in scg_folders:
            #     for name in content:
            #         if folder.split('-')[1] in name and folder.split('-')[0] != name.split('-')[0]:
            #             need_rename = True
            #             break
            #     if need_rename:
            #         break
            #
            # if need_rename:
            #     print(f"命令参考目录下的文件夹：")
            for name in content:
                match_found = False
                for folder in scg_folders:
                    if name.split('-')[1] in folder:
                        match_found = True
                if not match_found:
                    print(f"\033[93m警告：命令参考分册 {name} 缺失\033[0m")
                    sysop_flag = True
            for folder in scg_folders:
                found_match = False
                for name in content:
                    if "-" in folder:
                        if folder.split('-')[1] in name:
                            found_match = True
                            if folder.split('-')[0] == name.split('-')[0]:
                                continue
                            else:
                                try:
                                    old_path = os.path.join(cref_path, folder)
                                    new_path = os.path.join(cref_path, name)
                                    if flag:
                                        # 使用 SVN 命令重命名
                                        subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                    else:
                                        os.rename(old_path, new_path)
                                    print(f"重命名命令参考分册: {folder} -> {name}")
                                    for i, updated_path in enumerate(updated_paths):
                                        if old_path in updated_path:
                                            updated_paths[i] = updated_path.replace(old_path, new_path)
                                except Exception as e:
                                    print(f"\033[91m重命名命令参考文件夹失败:\033[0m {str(e)}")
                                    sysop_flag = True
                    else:
                        if folder in name:
                            found_match = True
                            try:
                                old_path = os.path.join(cref_path, folder)
                                new_path = os.path.join(cref_path, name)
                                if flag:
                                    # 使用 SVN 命令重命名
                                    subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                else:
                                    os.rename(old_path, new_path)
                                print(f"重命名命令参考分册: {folder} -> {name}")
                                for i, updated_path in enumerate(updated_paths):
                                    if old_path in updated_path:
                                        updated_paths[i] = updated_path.replace(old_path, new_path)
                            except Exception as e:
                                print(f"\033[91m重命名命令参考文件夹失败:\033[0m {str(e)}")
                                sysop_flag = True
                if not found_match:
                    print(f"\033[93m警告：扉页中未找到命令参考分册 {folder}\033[0m ")
                    sysop_flag = True
        else:
            print(f"\033[91m错误：找不到命令参考目录:\033[0m {cref_path}")
            sysop_flag = True

    except Exception as e:
        print(f"\033[91m处理文件出错:\033[0m {str(e)}")
        print(f"\033[91m遍历文件夹出错:\033[0m {str(e)}")
        sysop_flag = True
    if is_only_dir:
        print("程序执行完成!!!")
        return "-1"
    else:
        print("*" * 50)
        # print(updated_paths)
        return updated_paths, sysop_flag


if __name__ == '__main__':
    module_level_number(True, True)
